<template>
<div class="pop zeal-chat">
        <div class="zeal-chat-contant" style="height: 390px">
            <section class="ui-container" ref="homePage">
                <ul class="chat-message">
                    <li v-for="(chat,index) in chatList" :class="chat.type === 'service' ? 'an-move-right' : 'an-move-left'" >
                        <p class="time">{{chat.date}}</p>
                        <div class="main">
                            <i class="user-image"></i>
                           <chat-message :message='chat.message' :index='index' :msgType='chat.msgType' :fileurl="chat.fileurl" :mediaId='chat.mediaId'></chat-message>
                        </div>
                    </li>

                </ul>
            </section>
        </div>
        <div class="line"></div>
    <div class="webeditor">
        <div class="tools">
        </div>
        <div class="z_file" onclick="document.getElementById('file').click()">
            <input style="display: none;" type="file" name="file" id="file" value="" accept="image/gif,image/jpg,image/jpeg,image/png"
                   @change="sendimg($event)">
        </div>
        <div class="z_file2" onclick="document.getElementById('file2').click()">
            <input style="display: none;" type="file" name="file2" id="file2" value="" @change="sendfile($event)">
        </div>
        <div class="tool-div" >
            <Dropdown  @on-click="commonPhrases" class="self-dropdown">
                <Button type="primary" style="background:rgba(58,152,255,1);width: 70px;height: 30px">
                  常用语
                  <Icon type="ios-arrow-down"></Icon>
                </Button>
                <DropdownMenu slot="list">
                  <DropdownItem v-for="(raw,index) in commonList" :name='raw.id' :key="index">{{raw.value}}</DropdownItem>
                </DropdownMenu>
              </Dropdown>
            <Button @click="sendMessage(false)" type="primary" class="send-button" style="background:rgba(58,152,255,1);width: 50px;height: 30px">发送</Button>
        </div>
        <div class="write_box">
            <div class="body" contenteditable="true"></div>
        </div>

    </div>
    <div v-show="showImg" class="window-shadow">

    </div>
    <div v-show="showImg" class="window-img" >
        <img @click="closeFullImg" class='close' src='../../static/img/close.png'>
        <img src="">
    </div>

  <message ref="message"></message>

</div>
</template>

<script>
  import ChatMessage from "./ChatMessage";
  import {dateStr} from "../tool/tool";
  import imchat from '../tool/imchat';
  import Message from "./Message";
  import arraytool from '../tool/tool';
  import {getsessiondetail} from "../api/api";
  import moment from 'moment';
  import {getBrowserClinetInfo} from "../tool/util";

  export default {
        name: "IM",
        components: {Message, ChatMessage},
        props:['chatList'],
        data(){
            return {
                 showImg: false,
                 commonList: [
                  {id:'1',value:'您好！很高兴为你服务，请问你需要办理什么业务?'},
                  {id:'2',value:'我们这边1年利息是3.5%,3年是4%，5年是5%'},
                  {id:'3',value:'请问您还有什么不清楚的地方吗?'},
                  {id:'4',value:'祝您生活幸福美满，阖家欢乐'},
                  {id:'5',value:'https://192.168.10.105/client/'},
                  {id:'6',value:'https://ivcs-demo.zealcomm.cn/client'}
                  ],
                  sessionId:null,//
                  agentccsClient:null,
                  ccsUrl:loginUrl,
                  ticket:null,
                  ccsinterval:null,
                  sessionmembers:[],
                  holdonmsgId:null,
                  needLeave:false,//转接是否需要离开
                  uploadurl:localStorage.getItem('uploadUrl'),
                  clientId:'',
            }
        },
        mounted (){
            var self = this;
            self.initEmotion();

            imchat.$on('removeAgent',()=>{
                self.sendMessageToAgent('systemDropAgent',0);
            });

            imchat.$on('readytotalk',function () {
              self.agentccsClient.readyToTalk('customers',function (status,result) {
                console.log('readyToTalk:',status);
                console.log(result);
              })
            });

            imchat.$on('photoGuideBox',function () {
               self.agentccsClient.photoGuideBox(true,'customers',function (status,result) {
                 console.log('photoGuideBox:',status);
                 console.log(result);
                 self.$Message.success('推送引导框成功');
               })
            });


            imchat.$on('sendcontract',function (data) {
               console.log(data);
               self.agentsendfile(data,true);
            });
            imchat.$on('handsign',function (data) {
              console.log(data);
              self.sendmessagetocustomer('please handsign',0);
              self.$Message.success('邀请已发出');
            });
            imchat.$on('screenshare',function (op) {
                if (op=='start'){
                    self.sendmessagetocustomer('sharescreenstart',0);
                } else if (op=='stop'){
                    self.sendmessagetocustomer('sharescreenstop',0);
                }
            });
            imchat.$on('sendCustomText',function(message){
              console.log('send customer text',message);
              self.sendmessagetocustomer(message,0);
            });
            imchat.$on('snapshot',function (imgurl) {
              console.log(imgurl);
              self.cccsendimg(imgurl);
            });

            imchat.$on('clientsnapshot',function () {
              self.agentccsClient.screenSnapshot(false,'customers',function (status,resp) {
                 console.log(resp);
                 if (status === 'ok'){
                   self.$Message.success('正在截取访客屏幕.');
                 } else{
                   self.$Message.error('截图失败');
                 }
              })
            });

            imchat.$on('transferagent',function (data) {
              self.agentccsClient.invite(data.data,function (status,resp) {
                console.log('invite data,',data);
                console.log('invite,',status);
                console.log(resp);
                if (status === "ok"){
                  self.needLeave = data.needleave;
                  if (data.needleave){
                      self.$Message.success('已转接给其他坐席...');
                      self.agentccsClient.holdOn('customers',function (status,resp,msgId) {
                          console.log('holdon,',status);
                          console.log(resp);
                          console.log('msgId,',msgId);
                          self.holdonmsgId = msgId;
                      });
                  }
                } else{
                    self.$Notice.error({
                        title: '温馨提示',
                        desc: '寻找其他坐席失败...',
                        duration:10,
                        top:0
                    });
                }
              });
            });



            imchat.$on('agentjoinccssession',function (data) {
              self.connectccs(data);
            });

            imchat.$on('quitccs',function () {
              self.quitccs();
            });

            imchat.$on('sendform',function () {
              self.agentccsClient.sendFormData({
                inputform:1
              },'customers',function (status,resp) {
                 console.log('send form ,',status);
                 console.log(resp);
                 if (status === 'ok'){
                   self.$Message.success('表单成功推送给访客.');
                 } else{
                   self.$Message.error('推送失败');
                 }
              })
            })

            imchat.$on('agenttellcustomer',function (data) {
              self.sendinstructiontocustomer(data);
            });



            imchat.$on('agentcollectioninfo',function (data) {
               self.agentccsClient.sendFormData(data,'customers',function (status,resp) {
                 console.log('send form ,',status);
                 console.log(resp);
                 if (status === 'ok'){
                   self.$Message.success("发送成功,等待访客确认·");
                 } else{
                   self.$Message.error('发送失败');
                 }
               });
            });

            imchat.$on('sendvideo',function (url) {
              self.agentccsClient.shareResource(url,'video','','customers',function (status,resp) {
                 console.log('send video,',status);
                 console.log(resp);
                 if (status === 'ok'){
                   self.$Message.success("发送成功");
                 } else{
                   self.$Message.error("发送失败");
                 }
              })
            });

            imchat.$on('sendlink',function (url) {
              self.agentccsClient.shareResource(url,'page','','customers',function (status,resp) {
                console.log('send video,',status);
                console.log(resp);
                if (status === 'ok'){
                  self.$Message.success("发送成功");
                } else{
                  self.$Message.error("发送失败");
                }
              })
            });

            imchat.$on('collectionPic',function (type) {
              self.sendmessagetocustomer('agentcollectionPic='+type,0);
            });



        },

        destroyed(){
          imchat.$off('agentjoinccssession');
          imchat.$off('quitccs');
          imchat.$off('endsession');
          imchat.$off('agenttellcustomer');
        },

        methods:{

           /*和CCC建立连接*/
           connectccs(data){
              //连接ccs
               //this.ccsUrl = ccsUrl;
               //data.url.publicUrl;
               this.sessionId = data.sessionId;
               this.agentccsClient = new ccsClient();
               this.agentccsClient.connect(this.ccsUrl,localStorage.getItem('token'));
               var self = this;
               let id = localStorage.getItem('userId');
               let name = localStorage.getItem('name');
               let org = localStorage.getItem('org');
               let clientInfo = getBrowserClinetInfo();
               const joinData ={
                   user: {id: id, name: name, org: org},
                   role: 'agent',
                   sessionId: this.sessionId,
                   clientInfo:clientInfo
               };
               console.log('join session data,',joinData);
               this.agentccsClient.joinSession(joinData, function(status, resp){
                 if(status === 'ok'){
                   console.log('joinSession:', resp);
                   self.ticket = resp.ticket;
                   self.sessionmembers = resp.members;
                   self.clientId = resp.clientId;
                   var ccs_ticket_refreshtime = resp.refershTicketTime;
                   console.log('now session members,',self.sessionmembers);
                   imchat.$emit('agentjoinroom',resp);
                   self.getsessionInfo(self.sessionId);
                   if (self.ccsinterval==null){
                         self.ccsinterval = setInterval(function () {
                             self.refreshticket();
                         },ccs_ticket_refreshtime);
                   }
                 } else {
                   console.log('joinSession error:', resp);
                   self.$Message.error(resp);
                   self.$Message.error('加入会话失败');
                 }
               });

               /*收到文字聊天消息*/
               this.agentccsClient.onTextMessage(function (data) {
                 console.log('onTextMessage:',data);
                 var message = data.data;
                 if(data.from != self.clientId && message === 'systemDropAgent'){
                    imchat.$emit('systemDropAgent');
                    return;
                 }
                 if (message === "inputformsuccess"){
                   imchat.$emit('inputformsuccess');
                   return;
                 } else if (message.indexOf('formid=')!=-1){
                   let formid = message.substring(7);
                   imchat.$emit('getforminfo',formid);//发送通知
                   return;
                 }else if(message === "collectionPicfailed"){
                   imchat.$emit('collectionPicfailed');
                   return;
                 }else{
                   var text = textFace2imgFace(message);
                   var result= {
                     type: 'customer',
                     date: dateStr(),
                     message: text
                   };
                   self.chatList.push(result);
                   self.scrollToBottom();
                 }
               });

               this.agentccsClient.onQuitSession(function (resp) {
                 console.log('onQuitSession:',resp);
                 var desc = "访客已离开";
                 for (let i =0;i<self.sessionmembers.length;i++){
                   if (resp.data.id === self.sessionmembers[i].id){
                     if (self.sessionmembers[i].role === 'agent'){
                       desc = "其他坐席已离开";
                       break;
                     }
                   }
                 }
                 self.$Notice.info({
                   title: '温馨提示',
                   desc: desc,
                   duration:120,
                   top:0
                 });
                 self.sessionmembers = arraytool.removeArrayWithid(self.sessionmembers,resp.data.id);
                 console.log('now session members,',self.sessionmembers);
               });


               this.agentccsClient.onSharedResource(function (resp) {
                 console.log('onshareResource,',resp);
                 if (resp.data.type === 'pic'){
                   //接收到照片
                   let message = '<img style="width:50px" src='+resp.data.url+'>';
                   let result = {
                     type: 'customer',
                     date: dateStr(),
                     message: message,
                     msgType: 'image',
                   };
                   self.chatList.push(result);
                   self.scrollToBottom();
                 } else if(resp.data.type === 'doc'){
                   let message = '<a href="javascript:void(0)">'+resp.data.name;
                   let result = {
                     type: 'customer',
                     date: dateStr(),
                     message: message,
                     msgType: 'file',
                     fileurl:resp.data.url,
                   };
                   self.chatList.push(result);
                   self.scrollToBottom();
                 }else if(resp.data.type === 'video'){
                     let message = '<a href="javascript:void(0)">'+resp.data.url;
                     let result = {
                         type: 'customer',
                         date: dateStr(),
                         message: message,
                         msgType: 'file',
                         fileurl:resp.data.url,
                     };
                     self.chatList.push(result);
                     self.scrollToBottom();
                 }
               });

               this.agentccsClient.onFormData(function (resp) {
                 console.log('onFormData:',resp);
               });


               this.agentccsClient.onHandwritingMessage(function (resp) {
                 imchat.$emit('handwriting',resp.data);
               });


               this.agentccsClient.onAck(function (resp) {
                  console.log('onAck:',resp);
                  if (self.holdonmsgId&&self.holdonmsgId === resp.data.id){
                    //访客收到 holdon消息
                    //imchat.$emit('holdonsuccess');
                  }
               });

               this.agentccsClient.onDrop(function (resp) {
                  console.log('onDrop,',resp);
                   self.$Notice.info({
                       title: '温馨提示',
                       desc: '本次通话已结束！！！',
                       duration:120,
                       top:0
                   });
                   imchat.$emit('dropsession');
               })


               this.agentccsClient.onJoinedSession(function (resp) {
                 console.log('onJoinedSession:',resp);
                 self.sessionmembers.push(resp.data);
                 console.log('now session members,',self.sessionmembers);
                 if(self.needLeave && resp.data && resp.data.role === 'agent'){
                      imchat.$emit('transferLeave');
                      self.needLeave = false;
                 }
               });

               this.agentccsClient.onInvitationProgress(function (resp) {
                   console.log('on Invitation Progress,',resp);
                   var status = resp.data.status;
                   if(status == "notfound"){
                       self.$Notice.error({
                           title: '温馨提示',
                           desc: '没有找到坐席！！！',
                           duration:10,
                           top:0
                       });
                       return;
                   }
                   if (self.needLeave){
                       if (status == "accepted"){
                           self.$Message.success('已转接给其他坐席...');
                           self.agentccsClient.holdOn('customers',function (status,resp,msgId) {
                               console.log('holdon,',status);
                               console.log(resp);
                               console.log('msgId,',msgId);
                               self.holdonmsgId = msgId;
                           });
                       }
                   }else{
                       if (status == "waiting"){
                           self.$Message.success('正在等待其他坐席接听...');
                       } else if (status == "connecting"){
                           self.$Message.success('其他坐席连接中...');
                       } else if (status == "accepted"){
                           self.$Message.success('其他坐席已接听...');
                       }
                   }
               });

               this.agentccsClient.onDisconnect(function(a, b){
                 console.log('ccs on Disconnect', a);
               });

               this.agentccsClient.onConnect(function (a) {
                 console.log('ccs addEventlistener-connect', a);
                 if (self.ticket){
                   //有票据了，重新链接的话就刷新connection
                   self.resumeconnect();
                 }
               });

               this.agentccsClient.onError(function (resp) {
                   console.log('ccs connect error',resp);
                   self.ccssystemError();
               });


            },

            /*ccs system have error*/
            ccssystemError(){
                this.$Notice.error({
                    title: '温馨提示',
                    desc: '系统异常...',
                    duration:3,
                    top:0
                });
                imchat.$emit('resumeconnectwithccsfailed');
                this.agentccsClient = null;
                clearInterval(self.ccsinterval);
                this.ccsinterval = null;
                this.ticket = null;
            },

            refreshticket(){
              var self = this;
              if (this.agentccsClient){
                this.agentccsClient.refreshTicket(function (status,resp) {
                  if (status === "ok"){
                    console.log(resp);
                    self.ticket = resp.ticket;
                    console.log('new ticket=',self.ticket);
                  }else{
                    self.ccssystemError();
                    console.log('refreshTicket failed');
                  }
                });
              }
            },


           getsessionInfo(sessionId){
             var self = this;
             getsessiondetail(sessionId).then(function (resp) {
                if (resp.data.code==200){
                  //init session data
                  self.initchatdata(resp.data.data.recordList.data);
                }
             }).catch(function (error) {
                 console.log(error);
             })
           },

           initchatdata(data){
             var self = this;
             for (const value of data) {
                 var fromType = value.role == "customer" ? "customer" : "service";//
                 var date = moment(value.createdAt).format('YYYY-MM-DD HH:mm:ss');
                 if (value.msgType === 'text') {
                   let result = {
                     type: fromType,
                     date: date,
                     message: value.data
                   };
                   if(value.data.indexOf('formid=')==-1){
                     self.chatList.push(result);
                   }
                 } else if (value.msgType === "peer-cmd") {
                   let result = {
                     type: fromType,
                     date: date,
                     message: value.data.cmd
                   };
                   self.chatList.push(result);
                 } else if (value.msgType === 'link') {
                   if (value.data.type === "pic") {
                     let message = '<img style="width:50px" src=' + value.data.url + '>';
                     let result = {
                       type: fromType,
                       date: date,
                       message: message,
                       msgType: 'image',
                     };
                     self.chatList.push(result);
                   } else if (value.data.type === "doc") {
                     let message = '<a href="javascript:void(0)">' + value.data.name;
                     let result = {
                       type: fromType,
                       date: date,
                       message: message,
                       msgType: 'file',
                       fileurl: value.data.url,
                     };
                     self.chatList.push(result);
                   } else if (value.data.type === "paper") {
                     let message = '推送合同:<a href="javascript:void(0)">' + value.data.name;
                     let result = {
                       type: fromType,
                       date: date,
                       message: message,
                       msgType: 'file',
                       fileurl: value.data.url,
                     };
                     self.chatList.push(result);
                   } else if (value.data.type === "video") {
                     let message = '推送视频地址:<a href="javascript:void(0)">' + value.data.url;
                     let result = {
                       type: fromType,
                       date: date,
                       message: message,
                       msgType: 'file',
                       fileurl: value.data.url,
                     };
                     self.chatList.push(result);
                   } else if (value.data.type === "page") {
                     let message = '推送链接地址:<a href="javascript:void(0)">' + value.data.url;
                     let result = {
                       type: fromType,
                       date: date,
                       message: message,
                       msgType: 'file',
                       fileurl: value.data.url,
                     };
                     self.chatList.push(result);
                   }
                 }
               }
               // })

           },



            resumeconnect(){
             var self = this;
              if (self.agentccsClient){
                self.agentccsClient.resumeConnection(self.ticket, function(status, resp){
                  if(status === 'ok'){
                    console.log('resume connect success');
                    console.log('resumeConnection:', JSON.stringify(resp));
                    self.ticket = resp.ticket;
                  } else {
                    console.log('resume connect failed');
                    console.log(status);
                    console.log(resp);
                    self.ccssystemError();
                  }
                });
              }
            },

           /*给客户发送一些互动指令信息 如：加入房间，坐席异常请访客挂断，冷转接，热转接*/
            sendinstructiontocustomer(data){
              let sendmessage = this.$refs.message.sendMessageFormat(data,'peer-status');
              this.agentccsClient.sendMessage(sendmessage, function(status, resp){
                if(status === 'ok'){
                  console.log('sendMessage Succeed!', resp);
                } else {
                  console.log('sendMessage failed', resp);
                  //TODO 异常处理？
                  //self.$Message.error('发送失败');
                }
              });
            },


          /*结束ccs会话*/
           quitccs(){
             var self = this;
             return new Promise(function (resolve, reject) {
               self.agentccsClient.quitSession(function(status, resp){
                 if(status === 'ok'){
                   console.log('quitSession Succeed!', resp);
                   self.agentccsClient = null;
                   clearInterval(self.ccsinterval);
                   self.ccsinterval = null;
                   self.ticket = null;
                   resolve(resp);
                 } else {
                   console.log('quitSession', resp);
                   self.agentccsClient = null;
                   clearInterval(self.ccsinterval);
                   self.ccsinterval = null;
                   self.ticket = null;
                   reject(resp);
                 }
               });
             })
           },


          /*发文字消息*/
          sendMessage(){
            var text = $('.body').html();
            if (text == '') {
              this.$Message.error("请输入信息！");
              $('.body').focus();
              return;
            }
            console.log(text);
            var content =imgFace2textFace(text.replace(/<br>/ig, '\n').replace(
              /<div>/ig, '\n').replace(/<(?!img|embed).*?>/ig, '').replace(
              /&nbsp;/ig, ' '));
            this.sendmessagetocustomer(content);
          },

          /*发送常用语*/
          commonPhrases(value){
            var message = '';
            if (value == 1){
              message = this.commonList[0].value;
            }else if (value == 2){
              message = this.commonList[1].value;
            }else if (value == 3){
              message = this.commonList[2].value;
            }else if (value == 4){
              message = this.commonList[3].value;
            }
            else if (value == 5){
              message = this.commonList[4].value;
            }
            else if (value == 6){
              message = this.commonList[5].value;
            }
            this.sendmessagetocustomer(message);
          },

          sendmessagetocustomer(message,needaddhistory){
            var self = this;
            if (this.agentccsClient){
            this.agentccsClient.sendTextMessage(message,'customers',function (status,resp,msgId) {
              if(status === 'ok'){
                console.log('sendMessage Succeed!', resp);
                console.log('msgid,',msgId);
                if (needaddhistory!=0){
                  self.chatList.push({
                    type: 'service',
                    message: textFace2imgFace(message),
                    date: dateStr()
                  })
                }
                $('.body').html('');
                self.scrollToBottom();
              } else {
                console.log('sendMessage', resp);
                self.$Message.error('发送失败');
              }
            });
            }
          },


    sendMessageToAgent(message,needaddhistory){
            var self = this;
            if (this.agentccsClient){
                this.agentccsClient.sendTextMessage(message,'agents',function (status,resp,msgId) {
                  if(status === 'ok'){
                    console.log('sendMessage Succeed!', resp);
                    console.log('msgid,',msgId);
                    if (needaddhistory!=0){
                      self.chatList.push({
                        type: 'service',
                        message: textFace2imgFace(message),
                        date: dateStr()
                      })
                    }
                    $('.body').html('');
                    self.scrollToBottom();
                  } else {
                    console.log('sendMessage', resp);
                    self.$Message.error('发送失败');
                  }
            });
            }
      },

            /*发图片*/
            sendimg(event){
                var self = this;
                var formData = new FormData();
                self.loading('正在发送...');
                formData.append('file', document.getElementById("file").files[0]);
                $.ajax({
                    url: self.uploadurl,
                    type: 'POST',
                    data: formData,
                    timeout:  60000, //超时时间设置，单位毫秒 默认60s
                    contentType: false,
                    processData: false,
                    error: function (error) {
                        console.log('upload error!',error);
                        self.$Spin.hide();
                        self.$Message.error('图片发送失败');
                    },
                    success: function (res) {
                        if (res.code == 200) {
                            console.log('upload success');
                            self.cccsendimg(res.data.url);
                        } else {
                            console.log('upload error! !=200');
                            self.$Message.error('图片发送失败');
                        }
                        self.$Spin.hide();
                    }
                });
                event.target.value = null;
            },

           /*根据url发送图片*/
            cccsendimg(url){
              let message = '<img style="width:50px" src='+url+'>';
              this.sendimagetocustomer(message,url);
          },

           sendimagetocustomer(imagemessage,url){
            var self = this;
              this.agentccsClient.shareResource(url,'pic','imagename','customers',function (status,resp) {
                if(status === 'ok'){
                  console.log('send image Message Succeed!', resp);
                  self.chatList.push({
                    type: 'service',
                    message: imagemessage,
                    date: dateStr(),
                    msgType: 'image'
                  });
                  $('.body').html('');
                  self.scrollToBottom();
                } else {
                  console.log('sendMessage', resp);
                  self.$Message.error('发送失败');
                }
              })

          },




            /*chat发文件*/
          sendfile(event){
              var formData = new FormData();
              formData.append('file', document.getElementById("file2").files[0]);
              console.log(formData);
              this.agentsendfile(formData);
              event.target.value = null;
            },

          loading(text){
              this.$Spin.show({
                  render: (h) => {
                      return h('div', [
                          h('Icon', {
                              'class': 'demo-spin-icon-load',
                              props: {
                                  type: 'ios-loading',
                                  size: 18
                              }
                          }),
                          h('div', text)
                      ])
                  }
              });
          },

          agentsendfile(data,iscontract){
            var self = this;
            self.loading('正在发送');
            $.ajax({
              url: self.uploadurl,
              type: 'POST',
              data: data,
              timeout:  60000, //超时时间设置，单位毫秒 默认60s
              contentType: false,
              processData: false,
              error: function (error) {
                console.log('upload error!',error);
                self.$Spin.hide();
                self.$Message.error('文件发送失败');
              },
              success: function (res) {
                if (res.code == 200) {
                  console.log('upload success');
                  if (iscontract){
                    //发送pdf合同
                    self.sendcontracttocustomer(res.data.originalname,res);
                  } else{
                    let message = '<a href="javascript:void(0)">'+res.data.originalname;
                    self.sendfiletocustomer(message,res);
                  }
                } else {
                  console.log('upload error! !=200');
                  self.$Message.error('文件发送失败');
                }
                self.$Spin.hide();
              }
            });
          },

          sendfiletocustomer(filemessage,res){
            var self = this;
            var url = res.data.url;
            this.agentccsClient.shareResource(url,'doc',res.data.originalname,'customers',function (status,resp) {
              if(status === 'ok'){
                console.log('send file Message Succeed!', resp);
                self.chatList.push({
                  type: 'service',
                  message: filemessage,
                  date: dateStr(),
                  msgType: 'file',
                  fileurl:res.data.url,
                });
                $('.body').html('');
                self.scrollToBottom();
              } else {
                console.log('send file Message', resp);
                self.$Message.error('发送失败');
              }
            })
          },

          /*发送合同信息给访客*/
          sendcontracttocustomer(filemessage,res){
            var self = this;
            let fileurl = res.data.url;
            this.agentccsClient.shareResource(fileurl,'paper',filemessage,'customers',function (status,resp) {
              if(status === 'ok'){
                self.$Message.success('发送成功');
                console.log('send pdf Succeed!', resp);
              } else {
                console.log('send pdf Message', resp);
                self.$Message.error('发送失败');
              }
            })
          },




          /*UI滑动*/
          scrollToBottom() {
             var speak_height = $('.chat-message').height();
              speak_height = speak_height + 100;
              $('.ui-container,.zeal-chat-contant').animate({
                  scrollTop: speak_height
              }, 500);
          },

            /*初始化表情设置*/
            initEmotion() {
                    var that = this;
                    var editorTools = {
                        'emotion': '<div class="emotion" onmousedown="return false" unselectable="on"></div>'
                    };
                    var editorObject = {
                        bindBody: false,
                        options: {
                            maxInputNum: 10000
                        },
                        init: function(selector, options) {
                            var self = this;
                            self.dom = $(selector);
                            self.parentTextAreaDom = $(window.parent.document).find('#' + that.getQueryString('id'));
                            self.initBody(self);
                            self.initTools(self, options);
                            self.initToolsEvents(self);
                        },
                        initTools: function(self, options) {
                            if (!options || !options.tools) return;
                            var toolsDom = self.dom.find('.tools');
                            toolsDom.attr({
                                'unselectable': 'on',
                                'onmousedown': 'return false'
                            });
                            for (var i in options.tools) {
                                var key = options.tools[i];
                                toolsDom.append(editorTools[key]);
                            }
                            var emotion = self.dom.find('.tools .emotion');
                            if (emotion.length > 0) {
                                var navtools = $('<ul class="nav"></ul>');
                                for (var i = 1, j = 0; i + j < 132; i += 10) {
                                    var li = $('<li></li>');
                                    for (var j = 0; j < 10 && i + j < 132; j++) {
                                        var index = i + j;
                                        var src = 'static/image/editor/emotion/qq/' + index + '.gif';
                                        li.append('<img src="' + src + '" onmousedown="return false" unselectable="on" >');
                                    }
                                    navtools.append(li);
                                }
                                emotion.append(navtools);
                            }
                        },
                        initBody: function(self) {
                            var bodyDom = self.dom.find('.body').attr('contentEditable', 'true');
                            if (!self.bindBody) {
                                self.bindBody = true;
                                $('body').on('click', function(event) {
                                    that.stopPropagation(event);
                                    $(this).find('.nav').fadeOut();
                                });
                            }

                            bodyDom.keyup(function() {
                                var html = $(this).html();
                                self.parentTextAreaDom.val(html);

                                var len = html.length;
                                self.dom.find('.bottom .inputInfo .doneNum').text(len);
                                var unDoneLength = self.options.maxInputNum - len;
                                self.dom.find('.bottom .inputInfo .undoNum').text(unDoneLength);
                            });
                        },
                        initToolsEvents: function(self) {
                            self.dom.find('.tools').on('click', '.emotion', function(event) {
                                that.stopPropagation(event);
                                $(this).find('.nav').show();
                            })
                            self.dom.find('.tools').on('click', '.emotion .nav img', function(event) {
                                that.stopPropagation(event);
                                var src = $(this).attr('src');
                                var html = '<img src="' + src + '"> ';
                                that.insertAtCursor(self.dom.find('.body')[0], html);
                                self.dom.find('.body').keyup(); // 触发一下
                                self.dom.find('.nav').hide();
                            });
                        }

                    };

                    editorObject.init('.webeditor', {
                        'tools': ['emotion']
                    });
                },

            getQueryString(name) {
                    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                    var r = window.location.search.substr(1).match(reg);
                    if (r != null) return unescape(r[2]);
                    return null;
            },


            stopPropagation(event) {
                    if (event.stopPropagation) {
                        // this code is for Mozilla and Opera
                        event.stopPropagation();
                    } else if (window.event) {
                        // this code is for IE
                        window.event.cancelBubble = true;
                    }
                },

            insertAtCursor(dom, html) {
                    if (dom != document.activeElement) {
                        dom.innerHTML = dom.innerHTML + html;
                        return;
                    }
                    var sel, range;
                    if (window.getSelection) {
                        // IE9 或 非IE浏览器
                        sel = window.getSelection();
                        if (sel.getRangeAt && sel.rangeCount) {
                            range = sel.getRangeAt(0);
                            range.deleteContents();
                            // Range.createContextualFragment() would be useful here but is
                            // non-standard and not supported in all browsers (IE9, for one)
                            var el = document.createElement("div");
                            el.innerHTML = html;
                            var frag = document.createDocumentFragment(),
                                node, lastNode;
                            while ((node = el.firstChild)) {
                                lastNode = frag.appendChild(node);
                            }
                            range.insertNode(frag);
                            // Preserve the selection
                            if (lastNode) {
                                range = range.cloneRange();
                                range.setStartAfter(lastNode);
                                range.collapse(true);
                                sel.removeAllRanges();
                                sel.addRange(range);
                            }
                        }
                    } else if (document.selection && document.selection.type != "Control") {
                        // IE < 9
                        document.selection.createRange().pasteHTML(html);
                    }
                },

            return2Br(str) {
                        return str.replace(/\r?\n/g, "<br />");
                },

            showFullImg(src){
                    $('.window-img').find('img')[1].src = src;
                    this.showImg = true;
                },

            closeFullImg(){
                    this.showImg = false;
                },

        }
    }
</script>

<style scoped>
    @import "../../static/css/gdt-style.css";
    @import "../../static/css/im.css";
</style>
